package j2se.dynamicProxy;

import org.directwebremoting.util.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by jingqing.zhou on 2015/6/2.
 */
public class DynamicProxy implements InvocationHandler {
    Logger logger = Logger.getLogger(DynamicProxy.class);
    private Object delegate ;//要处理的被代理对象
    private Object proxy ; //操作者

    /**
     *
     * @param delegate
     * @param proxy
     * @return
     */
    public Object bind(Object delegate , Object proxy){
        this.delegate = delegate ;
        this.proxy = proxy ;
        /**
         * 得到一个动态的代理对象
         */
        return Proxy.newProxyInstance(
                this.delegate.getClass().getClassLoader(),
                this.delegate.getClass().getInterfaces(),
                this
        );

    }

    /**
     *
     * @param proxy 这里的proxy就是操作日志类==》LoggerOperation
     * @param method 反射类Method实例
     * @param args 方法参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        try {
            Class clazz = this.proxy.getClass();
            Method start = clazz.getDeclaredMethod("start",new Class[]{Method.class});
            start.invoke(this.proxy,new Object[]{method});
            result = method.invoke(this.delegate,args);
            Method end = clazz.getDeclaredMethod("end",new Class[]{Method.class});
            end.invoke(this.proxy,new Object[]{method});
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
